package com.example.sistemacompras;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.example.sistemacompras.db.DatabaseHandler;
import com.example.sistemacompras.entity.Client;
import com.example.sistemacompras.entity.Product;
import com.example.sistemacompras.utils.Utils;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class ProductUpdateActivity extends Activity {

	private int mId;
	private Client mClient;

	private DatabaseHandler db;

	private EditText mNameWid;

	private EditText mDescriptionWid;

	private EditText mUnitValueWid;

	private ImageView mPhotoWid;

	private EditText mQtdStockWid;

	private String mName;

	private String mDescription;

	private float mUnitValue;

	private Bitmap mPhoto = null;

	private Uri fileUri = null;

	private static final int CAPTURE_IMAGE_ACTIVITY_REQ = 0;

	private long mQtdStock;

	private String mCurrentPhotoPath;
	private int mProductId;
	private Product mProduct;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_product_update);
		if (db == null) {
			db = new DatabaseHandler(getApplicationContext());
		}
		mNameWid = (EditText) findViewById(R.id.pdt_name_edit);
		mNameWid.setText("");
		mDescriptionWid = (EditText) findViewById(R.id.pdt_description_edit);
		mDescriptionWid.setText("");
		mUnitValueWid = (EditText) findViewById(R.id.pdt_unit_value_edit);
		mUnitValueWid.setText("");
		mPhotoWid = (ImageView) findViewById(R.id.pdt_up_photo);
		mPhotoWid.setImageDrawable(getResources()
				.getDrawable(R.drawable.photo_holder));
		mQtdStockWid = (EditText) findViewById(R.id.pdt_stock_edit);
		mQtdStockWid.setText("");

		mPhoto = ((BitmapDrawable) ((ImageView) findViewById(R.id.pdt_up_photo))
				.getDrawable()).getBitmap();
		mCurrentPhotoPath = null;
		mId = getIntent().getExtras().getInt("user_id");
		mProductId = getIntent().getExtras().getInt("pdt_id");

		mClient = db.getClientById(mId);
		mProduct = db.getProductById(mProductId);

		mNameWid.setText(mProduct.getName());
		mDescriptionWid.setText(mProduct.getDescription());
		mUnitValueWid.setText(String.valueOf(mProduct.getUnitValue()));
		mPhotoWid.setImageDrawable(getResources()
				.getDrawable(R.drawable.images));
		mQtdStockWid.setText(String.valueOf(mProduct.getQtdStock()));

		((ImageView) findViewById(R.id.pdt_up_photo)).setImageBitmap(mPhoto);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
	}

	public void atualizarProduto(View view) {
		mName = mNameWid.getText().toString();
		mDescription = mDescriptionWid.getText().toString();
		mUnitValue = Float.parseFloat(mUnitValueWid.getText().toString());
		mQtdStock = Long.parseLong(mQtdStockWid.getText().toString());

		Product product = new Product();
		product.setId(mProductId);
		product.setName(mName);
		product.setDescription(mDescription);
		product.setUnitValue(mUnitValue);
		product.setQtdStock(mQtdStock);
		product.setClient(mClient);

		if (mPhotoWid != null) {
			Utils util = new Utils(this);
			int proportion = 6;
			int width = util.getWidthInPixels() / proportion;
			int height = util.getHeightInPixels() / proportion;
			mPhoto = getResizedBitmap(
					(Bitmap) ((BitmapDrawable) mPhotoWid.getDrawable())
							.getBitmap(),
					width, height);

			product.setPhoto(mPhoto);
		}

		db.updateProduct(product);

		finish();
	}

	static final int REQUEST_TAKE_PHOTO = 1;

	@SuppressLint("SimpleDateFormat")
	private File createImageFile() throws IOException {
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		String imageFileName = "JPEG_" + timeStamp + "_";
		File storageDir = Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
		File image = File.createTempFile(imageFileName, /* prefix */
				".jpg", /* suffix */
				storageDir /* directory */
		);
		try {
			mCurrentPhotoPath = getPath(this,
					Uri.parse(image.toURI().toString()));

		} catch (URISyntaxException e) {
			e.printStackTrace();
		}

		return image;
	}

	public void shootPhoto(View view) {
		Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		fileUri = Uri.fromFile(getOutputPhotoFile());
		i.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
		startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQ);
	}

	@SuppressLint("SimpleDateFormat")
	private File getOutputPhotoFile() {
		File directory = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				getPackageName());
		if (!directory.exists()) {
			if (!directory.mkdirs()) {

				return null;
			}
		}
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date(0));
		return new File(directory.getPath() + File.separator + "IMG_"
				+ timeStamp + ".jpg");
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQ) {
			if (resultCode == RESULT_OK) {
				Uri photoUri = null;
				if (data == null) {
					Toast.makeText(this, "Image saved successfully",
							Toast.LENGTH_LONG).show();
					photoUri = fileUri;
				} else {
					photoUri = data.getData();
					Toast.makeText(this,
							"Image saved successfully in: " + data.getData(),
							Toast.LENGTH_LONG).show();
				}
				showPhoto(photoUri);
			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(this, "Callout for image capture failed!",
						Toast.LENGTH_LONG).show();
			}
		}
		// if (data != null) {
		// Log.wtf("TESTE", "Caiu no operations");
		// Intent returnIntent = new Intent();
		// returnIntent.putExtra("excluido", true);
		// setResult(RESULT_OK, returnIntent);
		// }
	}

	private void showPhoto(Uri photoUri) {

		File imageFile = new File(photoUri.getEncodedPath());
		if (imageFile.exists()) {
			Drawable oldDrawable = mPhotoWid.getDrawable();
			Utils util = new Utils(this);
			int proportion = 6;
			int width = util.getWidthInPixels() / proportion;
			int height = util.getHeightInPixels() / proportion;
			mPhoto = getResizedBitmap(
					BitmapFactory.decodeFile(imageFile.getAbsolutePath()),
					width, height);
			if (oldDrawable != null) {
				((BitmapDrawable) oldDrawable).getBitmap().recycle();
			}
			BitmapDrawable drawable = new BitmapDrawable(this.getResources(),
					mPhoto);
			mPhotoWid.setScaleType(ImageView.ScaleType.FIT_CENTER);
			mPhotoWid.setImageDrawable(drawable);

		}
	}

	public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {

		int width = bm.getWidth();

		int height = bm.getHeight();

		float scaleWidth = ((float) newWidth) / width;

		float scaleHeight = ((float) newHeight) / height;

		Matrix matrix = new Matrix();

		matrix.postScale(scaleWidth, scaleHeight);
		matrix.postRotate(90.0f);

		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
				matrix, false);

		return resizedBitmap;

	}

	public static String getPath(Context context, Uri uri)
			throws URISyntaxException {
		if ("content".equalsIgnoreCase(uri.getScheme())) {
			String[] projection = { "_data" };
			Cursor cursor = null;

			try {
				cursor = context.getContentResolver().query(uri, projection,
						null, null, null);
				int column_index = cursor.getColumnIndexOrThrow("_data");
				if (cursor.moveToFirst()) {
					return cursor.getString(column_index);
				}
			} catch (Exception e) {
				// Eat it
			}
		} else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}

		return null;
	}

}
